//
//  PostMessageViewController.m
//  SIPphone
//
//  Created by wrt on 13-11-11.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "PostMessageViewController.h"
#import "PostTextMsgViewController.h"
#import "PostPictureViewController.h"
#import "PostVideoViewController.h"
#import "PostMessageDataBase.h"
#import "PostMessage.h"


@interface PostMessageViewController ()
@property (assign, nonatomic) int begin;

@end

@implementation PostMessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"push message", @"推送信息 Push message");
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    //当界面刷新时再次读取数据刷新tableView
    [super viewWillAppear:animated];
//    PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
//    [postMsgDB loadArray];
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.begin = 0;
    // Do any additional setup after loading the view from its nib.
    PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
    [postMsgDB loadArray];
    [postMsgDB readDBForpartWithBeginNumber:self.begin];
    
    self.timeArray = [[NSMutableArray alloc] init];
    self.textArray = [[NSMutableArray alloc] init];
    self.statusArray = [[NSMutableArray alloc] init];
    self.pathArray = [[NSMutableArray alloc] init];
    self.noticeArray = [[NSMutableArray alloc] init];
    self.kindArray = [[NSMutableArray alloc] init];
    
    [self.timeArray addObjectsFromArray:postMsgDB.partTimeArray];
    [self.textArray addObjectsFromArray:postMsgDB.partTextArray];
    [self.statusArray addObjectsFromArray:postMsgDB.partStatusArray];
    [self.pathArray addObjectsFromArray:postMsgDB.partPathArray];
    [self.noticeArray addObjectsFromArray:postMsgDB.partNoticeArray];
    [self.kindArray addObjectsFromArray:postMsgDB.partKindArray];
    
    
    
    //删除编辑按钮
    UIBarButtonItem *deleteButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"editor", @"编辑 Editor") style:UIBarButtonItemStyleBordered target:self action:@selector(deleteButtonPressed)];
    self.navigationItem.rightBarButtonItem = deleteButton;
    
    //设置通知来刷新界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadtableView:) name:@"RELOADTABLEVIEWPOSTMSG" object:nil];
}

//编辑按钮操作
- (void)deleteButtonPressed
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"取消 cancel") destructiveButtonTitle:NSLocalizedString(@"clear All Records", @"清除全部记录 Clear All Records") otherButtonTitles:NSLocalizedString(@"clear single record", @"清除单个记录 Clear single record"), nil];
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow]; //这么加进去就不会“取消”按钮按了没反应
}

#pragma mark -
#pragma mark tableViewDelegateMethod

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.timeArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
//    if (indexPath.row == self.timeArray.count)
//    {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"testCell"];
//        cell.textLabel.textAlignment = 1;
//        cell.textLabel.textColor = [UIColor grayColor];
//        cell.textLabel.text = @"点击加载更多";
//        cell.backgroundColor = [UIColor clearColor];
//        
//        cell.detailTextLabel.text = nil;
//        cell.imageView.image = nil;
//        cell.editing = NO;
//        cell.tag = 128513;
//        return cell;
//    }
    
    //判断是什么消息
    if ([self.noticeArray[indexPath.row] isEqualToString:@"advert"])
    {
        cell.textLabel.text = NSLocalizedString(@"advertising message", @"广告消息 Advertising message");
    }
    else if([self.noticeArray[indexPath.row] isEqualToString:@"notice"])
    {
        cell.textLabel.text = NSLocalizedString(@"notification message", @"通知消息 Notification message");
    }
    
    
    //判断是什么类型的消息
    if ([self.kindArray[indexPath.row] isEqualToString:@"text"])
    {
        cell.imageView.image = [UIImage imageNamed:@"attibutes.png"];
    }
    else if ([self.kindArray[indexPath.row] isEqualToString:@"picture"])
    {
        cell.imageView.image = [UIImage imageNamed:@"image_msg_32.png"];
    }
    else if ([self.kindArray[indexPath.row] isEqualToString:@"video"])
    {
        cell.imageView.image = [UIImage imageNamed:@"movie_32.png"];
    }
    
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    //判断是否是未读 若未读则为蓝色字体
    if ([self.statusArray[indexPath.row] isEqualToString:@"未读"])
    {
        cell.textLabel.textColor = [UIColor blueColor];
        cell.detailTextLabel.textColor = [UIColor blueColor];
    }
    
    //对应的时间
    NSString *tempTimeCell = [[NSString alloc] init];
    tempTimeCell = self.timeArray[indexPath.row];
    
    //文本
    NSString *tempTextCell = [[NSString alloc] init];
    tempTextCell = self.textArray[indexPath.row];
    
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@/%@",tempTimeCell,tempTextCell];
    
    cell.tag = indexPath.row + 1;
    
    return cell;
}

//cell选择后的处理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
    
    
    //获取选择的cell是哪一个
    UITableViewCell *cell = (UITableViewCell *)[self.view viewWithTag:(indexPath.row + 1)];
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    //若是未读状态 则将其对应数据库里面的状态改成“已读”
    if ([self.statusArray[indexPath.row] isEqualToString:@"未读"])
    {
        [postMsgDB editStatusWithTime:self.timeArray[indexPath.row] andText:self.textArray[indexPath.row]];
        [self.statusArray replaceObjectAtIndex:indexPath.row withObject:@"已读"];
    }
    
    //分别对应种类弹出界面
    if ([self.kindArray[indexPath.row] isEqualToString:@"text"])
    {
        //文本类型
        PostTextMsgViewController *postTextMsgVC = [[PostTextMsgViewController alloc] initWithNotice:self.noticeArray[indexPath.row] andText:self.textArray[indexPath.row] andTime:self.timeArray[indexPath.row]];
        
        [self.navigationController pushViewController:postTextMsgVC animated:YES];
    }
    else if ([self.kindArray[indexPath.row] isEqualToString:@"picture"])
    {
        //图片类型
        PostPictureViewController *postPicVC = [[PostPictureViewController alloc] initWithNotice:self.noticeArray[indexPath.row] andText:self.textArray[indexPath.row] andTime:self.timeArray[indexPath.row] andURL:self.pathArray[indexPath.row]];
        
        [self.navigationController pushViewController:postPicVC animated:YES];
    }
    else if ([self.kindArray[indexPath.row] isEqualToString:@"video"])
    {
        //视频类型
        PostVideoViewController *postVideoVC = [[PostVideoViewController alloc] initWithNotice:self.noticeArray[indexPath.row] andText:self.textArray[indexPath.row] andTime:self.timeArray[indexPath.row] andURL:self.pathArray[indexPath.row]];
        [self.navigationController pushViewController:postVideoVC animated:YES];
    }
    
}

//编辑模式下可删除的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.timeArray.count)
    {
        return;
    }
    else
    {
        //数据库执行删除
        PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
        [postMsgDB deleteWithTime:self.timeArray[indexPath.row] andText:self.textArray[indexPath.row]];
        
        //删除掉对应数组内的内容
        [self.timeArray removeObjectAtIndex:indexPath.row];
        [self.textArray removeObjectAtIndex:indexPath.row];
        [self.statusArray removeObjectAtIndex:indexPath.row];
        [self.pathArray removeObjectAtIndex:indexPath.row];
        [self.noticeArray removeObjectAtIndex:indexPath.row];
        [self.kindArray removeObjectAtIndex:indexPath.row];
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }
}

#pragma mark -
#pragma mark actionSheetMethod
//UIActionSheet 对应按钮的操作
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        //数据库执行删除
        PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
        [postMsgDB removeAll];
        [self.timeArray removeAllObjects];
        [self.textArray removeAllObjects];
        [self.statusArray removeAllObjects];
        [self.pathArray removeAllObjects];
        [self.noticeArray removeAllObjects];
        [self.kindArray removeAllObjects];
        [self.tableView reloadData];
    }
    if (buttonIndex == 1)
    {
        //进入编辑模式
        [self.tableView setEditing:!self.tableView.editing];
    }
    if (buttonIndex == 2)
    {
        
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.tableView.contentOffset.y >= self.tableView.contentSize.height - self.tableView.frame.size.height)
    {
        PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
        self.begin = self.timeArray.count;
        [postMsgDB readDBForpartWithBeginNumber:self.begin];
        
        [self.timeArray addObjectsFromArray:postMsgDB.partTimeArray];
        [self.textArray addObjectsFromArray:postMsgDB.partTextArray];
        [self.statusArray addObjectsFromArray:postMsgDB.partStatusArray];
        [self.pathArray addObjectsFromArray:postMsgDB.partPathArray];
        [self.noticeArray addObjectsFromArray:postMsgDB.partNoticeArray];
        [self.kindArray addObjectsFromArray:postMsgDB.partKindArray];
        
        
        [self.tableView reloadData];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)reloadtableView:(NSNotification *)notification
{
    
    dispatch_async(dispatch_get_main_queue(),^{
        
        PostMessage *postMsg = [[PostMessage alloc] init];
        postMsg = (PostMessage *)notification.object;
        [self.timeArray insertObject:postMsg.time atIndex:0];
        [self.textArray insertObject:postMsg.text atIndex:0];
        [self.statusArray insertObject:postMsg.status atIndex:0];
        [self.pathArray insertObject:postMsg.path atIndex:0];
        [self.noticeArray insertObject:postMsg.notice atIndex:0];
        [self.kindArray insertObject:postMsg.kind atIndex:0];
        
        //刷新表格
        [self.tableView reloadData];
    });
}

- (void)dealloc
{
    //取消通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RELOADTABLEVIEWPOSTMSG" object:nil];
}


@end
